package com.example.hystrixDemo.service.impl;

import com.netflix.hystrix.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class OrderHystrixCommand extends HystrixCommand<String>{

    Logger logger = LoggerFactory.getLogger(OrderHystrixCommand.class);
    @Autowired
    private OrderServiceImpl orderService;

    protected OrderHystrixCommand() {
        super(setter());
    }

    @Override
    protected String run() throws Exception {
        logger.info("OrderHystrixService.run Thread:{}", Thread.currentThread().getName());
        return orderService.queryByOrderId();
    }

    @Override
    protected String getFallback() {
        logger.info("OrderHystrixService.getFallback Thread:{}" , Thread.currentThread().getName());
        return "system is busy!";
    }

    /**
     * 熔断器设置
     * @return
     */
    private static Setter setter(){
        // 服务分组
        HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("orders");
        // 服务标识
        HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey("queryOrder");
        // 线程池名字
        HystrixThreadPoolKey threadPoolKey = HystrixThreadPoolKey.Factory.asKey("order-pool");
        HystrixThreadPoolProperties.Setter threadPoolPro = HystrixThreadPoolProperties.Setter()
                .withCoreSize(10)
                .withMaximumSize(20)
                .withKeepAliveTimeMinutes(5)
                .withQueueSizeRejectionThreshold(100);
        HystrixCommandProperties.Setter hystrixCommandProperties = HystrixCommandProperties.Setter()
                .withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.THREAD)
                .withExecutionTimeoutEnabled(false);

        Setter setter = Setter.
                withGroupKey(groupKey)
                .andCommandKey(commandKey)
                .andThreadPoolKey(threadPoolKey)
                .andThreadPoolPropertiesDefaults(threadPoolPro)
                .andCommandPropertiesDefaults(hystrixCommandProperties);
        return setter;
    }
}
